package com.shareware.common.timer

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.shareware.common.NUMBER_ONE

/**
 * desc: 倒计时
 * email: mobiledeveloper@qq.com
 */
abstract class AbstractDownTimer @JvmOverloads constructor(
    private val totalTime: Long,
    var timeStamp: Long = 1000,
    var interval: Long = 1000,
) {
    private val downTimeStart = NUMBER_ONE
    private var isStart: Boolean = false

    //剩余时间
    var remainTime: Long = totalTime

    /**
     * 是否暂停
     */
    var isPause: Boolean = true
        private set

    @SuppressLint("HandlerLeak")
    private val mDownTimeHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            synchronized(this@AbstractDownTimer) {
                if (isPause) {
                    return
                }
                if (msg.what == downTimeStart) {
                    remainTime -= timeStamp
                    if (remainTime < 0) {
                        onFinish()
                    } else {
                        onTick(remainTime, totalTime)
                        sendMessageDelayed(obtainMessage(downTimeStart), interval)
                    }
                }
            }
        }
    }

    /**
     * 倒计时开启
     */
    @Synchronized
    fun start() {
        if (isStart) {
            return
        }
        if (remainTime <= 0) {
            onFinish()
            return
        }
        isStart = true
        isPause = false
        mDownTimeHandler.sendMessage(mDownTimeHandler.obtainMessage(downTimeStart))
    }

    /**
     * 倒计时暂停
     */
    @Synchronized
    fun pause() {
        isPause = true
        isStart = false
        mDownTimeHandler.removeMessages(downTimeStart)
    }

    /**
     * 倒计时进行时，每秒触发一次
     */
    abstract fun onTick(millisUnFinished: Long, totalTime: Long)

    /**
     * 倒计时结束
     */
    abstract fun onFinish()
}